﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using FluentValidation;
using Mammoth.Reflections;
using Mammoth.ViewModels;

namespace Mammoth.Validations
{
    public class ValidationFactory
    {
        private static ValidationFactory instance;

        IDictionary<Type, IValidator> eValCache;

        public static ValidationFactory GetInstance()
        {
            return instance ?? (instance = new ValidationFactory());
        }

        private ValidationFactory()
        {
            eValCache = new Dictionary<Type, IValidator>();
        }

        public IValidator GetEntityValidator(INotifyPropertyChanged model)
        {
            var type = model.GetType();
            IValidator result;

            if (eValCache.TryGetValue(type, out result))
            {
                return result;
            }
            else
            {
                var validar = typeof(IValidator<>).MakeGenericType(type);
                var vTypes = model.GetType().Assembly.GetTypes()
                    .GetTypesByBaseClass(validar);
                if (vTypes.Count() == 0)
                    return null;
                var vInst = (IValidator) Activator.CreateInstance(vTypes.First());
                eValCache[type] = vInst;
                return vInst;
            }
        }
    }
}
